//
//  UINavigationController+TYStack.m
//  TYUIKit
//
//  Created by TuyaInc on 2019/10/28.
//

#import "UINavigationController+TYStack.h"

@implementation UINavigationController (TYStack)

#pragma mark - TY_Pop
- (BOOL)ty_canPopToSpecificViewController:(Class)cls {
    return [self ty_canPopToViewControllerWithKindOfClass:cls];
}

- (void)ty_popToSpecificViewController:(Class)cls animated:(BOOL)animated {
    [self ty_popToViewControllerWithKindOfClass:cls animated:animated];
}

- (BOOL)ty_canPopToViewControllerWithKindOfClass:(Class)cls {
    return [self ty_viewControllerWithKindOfClass:cls] != nil;
}

- (NSArray<__kindof UIViewController *> * __nullable)ty_popToViewControllerWithKindOfClass:(Class)cls animated:(BOOL)animated {
    UIViewController *vc = [self ty_viewControllerWithKindOfClass:cls];
    if (!vc) return nil;
    return [self popToViewController:vc animated:animated];
}

- (__kindof UIViewController * __nullable)ty_viewControllerWithKindOfClass:(Class)cls {
    UIViewController *target;
    for (UIViewController *vc in self.viewControllers) {
        if ([vc isMemberOfClass:cls]) {
            target = vc;
            break;
        } else if ([vc isKindOfClass:cls] && target == nil) {
            // 只匹配最先找到的 kindof 的 vc
            // 不能break，因为要继续查找 memberof
            target = vc;
        }
    }
    return target;
}

@end
